import { HttpException, Inject, Injectable, Logger } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { In, Repository } from 'typeorm';
import * as crypto from 'crypto';
import { JwtService } from '@nestjs/jwt';
import { Role } from './entities/role.entity';

function md5(str: string) {
    const hash = crypto.createHash('md5');
    hash.update(str);
    return hash.digest('hex');
}


@Injectable()
export class UserService {
    @Inject(JwtService)
    private jwtService: JwtService;

    @InjectRepository(Role)
    private roleRepository: Repository<Role>;



    @InjectRepository(User)
    private userRepository: Repository<User>;
    private logger = new Logger()

    /* 
    先根据 username 查找下，如果找到了，说明用户已存在，抛一个 HttpException 让 exception filter 处理。
    否则，创建 User 对象，调用 userRepository 的 save 方法保存。
    */
    async register(user: CreateUserDto) {
        // 先查找是否有相同的用户
        const { username, password } = user
        const foundUser = await this.userRepository.findOne({
            where: { username }
        })
        if (foundUser) {
            throw new HttpException('用户已存在', 200)
        }

        const newUser = this.userRepository.create(user)
        // newUser.password = md5(newUser.password) // 测试权限管理 暂时去掉密码加密

        try {
            return await this.userRepository.save(newUser)
        } catch (error) {
            this.logger.error(error, UserService)
            return "注册失败"
        }
    }

    async login(user: CreateUserDto) {
        const { username, password } = user

        if (!username || !password) {
            throw new HttpException('用户名或密码不能为空', 200)
        }

        const foundUser = await this.userRepository.findOne({
            where: { username },
            relations: ['roles']
        })
        if (!foundUser) {
            throw new HttpException('用户不存在', 200)
        }

        // 测试权限管理 暂时不用加密
        // if(foundUser.password !== md5(user.password)){
        //     throw new HttpException('密码错误', 200);
        // }

        if (foundUser.password !== user.password) {
            throw new HttpException('密码错误', 200);
        }
        if (foundUser) {
            const token = await this.jwtService.signAsync({
                user: {
                    id: foundUser.id,
                    roles: foundUser.roles.map((role) => role.id) // 存入时 只需要role的id
                }
            })
            await this.updateToken(foundUser.id, token)
            foundUser.token = token
        }
        return foundUser
    }

    updateToken(userid: number, token: string) {
        return this.userRepository.update({ id: userid }, { token });
    }

    findRolesById(ids: number[]) {
        return this.roleRepository.find({
            where: {
                id: In(ids)
            },
            relations: ['permissions']
        })
    }


    findAll() {
        return this.userRepository.find();
    }

    findOne(username: string) {
        return this.userRepository.findOne({ where: { username } , relations:['roles'] });
    }



    create(createUserDto: CreateUserDto) {
        return 'This action adds a new user';
    }

    update(id: number, updateUserDto: UpdateUserDto) {
        return `This action updates a #${id} user`;
    }

    remove(id: number) {
        return `This action removes a #${id} user`;
    }


}
